package org.zjt.spi;

import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.spi.ResourceBundleControlProvider;

/**
 * @author <a href="juntao.zhang@qq.com">juntao.zhang</a>
 * @Description:
 * @Package org.zjt.spi
 * @date 2017/12/4 15:46
 * @see
 */
public class Main {

    public static void main(String[] args) {
        ServiceLoader<IBaseService> load = ServiceLoader.load(IBaseService.class);
        Iterator<IBaseService> iterator = load.iterator();
        while (iterator.hasNext()){
            IBaseService next = iterator.next();
            System.out.println(next.echo("zhAng"));
        }
        System.out.println(loadService(ToLowerCaseBaseService.class).echo("liSi"));
    }


    /**
     * 从当前appclassloader开始加载spi。    {@link ServiceLoader#load(java.lang.Class)}
     * 从extclassloader开始加载spi。  {@link ServiceLoader#loadInstalled(java.lang.Class)}
     *
     *
     * @param t
     * @param <T>
     * @return
     */
    public static <T extends IBaseService>IBaseService  loadService(Class<T> t) {
        ServiceLoader<IBaseService> load = ServiceLoader.load(IBaseService.class);

        ServiceLoader.loadInstalled(ResourceBundleControlProvider.class);
        Iterator<IBaseService> iterator = load.iterator();
        while (iterator.hasNext()){
            IBaseService next = iterator.next();
            if (next.getClass().equals(t) )
            return next;
        }
        throw new IllegalArgumentException("未得到SPI服务实例");
    }
}
